<?php

namespace Api\Model;

use Think\Model;

class CouponListModel extends Model {

    /**
     * @name 获取用户优惠券
     * @param $userid
     * @param $longitude
     * @param $latitude
     * @param $num
     * @param $page
     * @return mixed
     */
    public function getCoupon($userid, $longitude, $latitude, $num, $page) {
        $start = $num * ($page - 1);
        $data = M('coupon_list as cl')->where("cl.user_id={$userid} and cl.status != 5")
                        ->join("cp_coupon as cp on cp.id=cl.coupon_id", 'LEFT')
                        ->join("cp_shops as shop on shop.id=cl.shops_id", 'LEFT')
                        ->field("cl.coupon_code , cl.status , max(cl.create_time) as create_time,
                cp.name,cp.discount,cp.start_time,cp.expired_time,
                shop.name as shop_name,shop.image,shop.longitude,shop.latitude,shop.tag
                ")->group('coupon_code')->limit($start, $num)->order('cl.create_time desc')->select();
        if ($data) {
            foreach ($data as $key => $val) {
                $data[$key]['distance'] = GetDistance($longitude, $latitude, $data[$key]['longitude'], $data[$key]['latitude']);
                unset($data[$key]['longitude']);
                unset($data[$key]['latitude']);
                unset($data[$key]['create_time']);
            }
        }
        return $data;
    }

    /**
     * @name 发布时获取优惠券详情
     * @param $userid
     * @param $couponCode
     */
    public function getPublishCouponInfo($userid, $couponCode, $longitude, $latitude) {
        //获取优惠券基础数据
        $couponInfo = $this->where("`user_id`={$userid} and `coupon_code`='{$couponCode}' ")->find();
        if ($couponInfo == false)
            return false;
        //获取优惠券关联数据
        $data = M('coupon as cp')->where("cp.id={$couponInfo['coupon_id']}")
                        ->join("cp_shops as shop on shop.id={$couponInfo['shops_id']}", 'LEFT')
                        ->field("'{$couponInfo['coupon_code']}' as coupon_code , '{$couponInfo['status']}' as status ,
                cp.name,cp.discount,cp.start_time,cp.expired_time,
                shop.name as shop_name,shop.image,shop.longitude,shop.latitude,shop.tag
                ")->find();
        if ($data) {
            $data['distance'] = GetDistance($longitude, $latitude, $data['longitude'], $data['latitude']);
            unset($data['longitude']);
            unset($data['latitude']);
            $data['receive_credit'] = getReceiveCredit($data['discount']);
        }
        return $data;
    }

    /**
     * @name 发布优惠券
     * @param $userid 用户id
     * @param $couponCode 优惠券码
     * @return array
     */
    public function publishCoupon($userid, $couponCode, $remark = null) {
        $return = array('status' => 0, 'msg' => null);
        $result = $this->where(" `coupon_code`='{$couponCode}' ")->order('create_time desc')->find();
        if ($result['user_id'] != $userid) {
            $return = array('status' => 0, 'msg' => '你不存在此优惠券，可能已被领取！');
        }

        switch ($result['status']) {
            case C('COUPON_STATUS.PUBLISH'):
                $return = array('status' => 0, 'msg' => '你已发布过此张优惠券，请勿重复发布！');
                break;
            case C('COUPON_STATUS.USE'):
                $return = array('status' => 0, 'msg' => '此优惠券已被使用！');
                break;
            case C('COUPON_STATUS.RECEIVE'):
                $return = array('status' => 1, 'msg' => '优惠券发布成功！');
                $this->where("`user_id`={$userid} and `coupon_code`='{$couponCode}' ")->save(array('status' => 3));
                //发布优惠券
                $this->savePath($userid, $couponCode, C('COUPON_STATUS.PUBLISH'), $remark);
                if ($remark != null) {
                    //更新用户积分
                    D('User')->saveUserCredit($userid, C('CREDIT_VALUE.PUBLISH_COUPON_REMARK'));
                    //记录积分日志
                    D('CreditLog')->addLog($userid, C('CREDIT_NAME.PUBLISH_COUPON_REMARK'), $couponCode, C('COUPON_STATUS.PUBLISH'), C('CREDIT_VALUE.PUBLISH_COUPON_REMARK'));
                }
                break;
        }

        return $return;
    }

    /**
     * @name 更新优惠券信息
     * @param $userid
     * @param $couponCode
     * @param $status
     * @param null $remark
     */
    public function savePath($userid, $couponCode, $status, $remark = null) {
        $data = array(
            'user_id' => $userid,
            'coupon_code' => $couponCode,
            'status' => $status,
            'remark' => $remark,
            'create_time' => time()
        );
        $this->where("`coupon_code`='{$couponCode}' and `user_id`={$userid}")->save($data);
    }

    /**
     * @name 新增优惠券信息
     * @param $userid
     * @param $couponCode
     * @param $status
     * @param null $remark
     * @param array $conponInfo
     */
    public function addPath($userid, $couponCode, $status, $remark = '', $conponInfo = array()) {
        $data = array(
            'shops_id' => $conponInfo['shops_id'],
            'user_id' => $userid,
            'coupon_code' => $couponCode,
            'coupon_id' => $conponInfo['coupon_id'],
            'status' => $status,
            'remark' => (string) $remark,
            'fid' => $conponInfo['id'],
            'create_time' => time()
        );
        $this->add($data);
    }

    /**
     * @name 删除优惠券
     * @param $couponCode
     * @param $userid
     */
    public function deleteCoupon($userid, $couponCode) {
        $couponInfo = $this->where("`user_id`={$userid} and `coupon_code`='{$couponCode}' ")->find();
        if ($couponInfo == false) {
            $this->last_msg('优惠券不存在！');
            return false;
        }
        if ($couponInfo['status'] == 5) {
            $this->last_msg('优惠券不存在！');
            return false;
        }
        if ($couponInfo['status'] == 2 || $couponInfo['status'] == 4) {
            $this->where("`user_id`={$userid} and `coupon_code`='{$couponCode}' ")->save(array('status' => 5));
            return true;
        } else {
            $this->last_msg('优惠券未被使用或未被领取无法删除！');
            return false;
        }
    }

    /**
     * @name 取消发布优惠券
     * @param $userid
     * @param $couponCode
     */
    public function cancelPublishCoupon($userid, $couponCode) {
        $status = $this->where("`user_id`={$userid} and `coupon_code`='{$couponCode}' ")->getField('status');
        if ($status) {
            switch ($status) {
                case 1:
                    $this->last_msg('优惠券未发布！');
                    return false;
                    break;
                case 2:
                    $this->last_msg('优惠券已被使用！');
                    return false;
                    break;
                case 3:
                    $this->where("`user_id`={$userid} and `coupon_code`='{$couponCode}' ")->save(array('status' => 1));
                    return true;
                    break;
                case 4:
                    $this->last_msg('无法取消，优惠券已被领取！');
                    return false;
                    break;
                case 5:
                    $this->last_msg('优惠券不存在！');
                    return false;
                    break;
            }
        } else {
            $this->last_msg('优惠券不存在！');
            return false;
        }
    }

    /**
     * @name 使用优惠券
     */
    public function useCoupon($userid, $couponCode) {
        $status = $this->where("`user_id`={$userid} and `coupon_code`='{$couponCode}' ")->getField('status');
        if ($status) {
            switch ($status) {
                case 1:
                    $this->where("`user_id`={$userid} and `coupon_code`='{$couponCode}' ")->save(array('status' => 2));
                    return true;
                    break;
                    $this->last_msg('优惠券未发布！');
                    return false;
                    break;
                case 2:
                    $this->last_msg('优惠券已被使用！');
                    return false;
                    break;
                case 3:
                    $this->last_msg('优惠券已发布，取消发布后才可使用！');
                    return false;
                    break;
                case 4:
                    $this->last_msg('优惠券已被领取！');
                    return false;
                    break;
                case 5:
                    $this->last_msg('优惠券不存在！');
                    return false;
                    break;
            }
        } else {
            $this->last_msg('优惠券不存在！');
            return false;
        }
    }

}
